"""
数据验证工具
"""

import re
from datetime import datetime


def validate_email(email):
    """验证邮箱格式"""
    if not email:
        return False
    
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return re.match(pattern, email) is not None


def validate_password(password):
    """验证密码强度"""
    if not password or len(password) < 8:
        return False
    
    # 检查是否包含字母和数字
    has_letter = re.search(r'[a-zA-Z]', password)
    has_digit = re.search(r'\d', password)
    
    return has_letter is not None and has_digit is not None


def validate_username(username):
    """验证用户名格式"""
    if not username or len(username) < 3 or len(username) > 20:
        return False
    
    # 只允许字母、数字、下划线
    pattern = r'^[a-zA-Z0-9_]+$'
    return re.match(pattern, username) is not None


def validate_phone(phone):
    """验证手机号格式"""
    if not phone:
        return False
    
    # 简单的手机号验证（可根据需要调整）
    pattern = r'^1[3-9]\d{9}$'
    return re.match(pattern, phone) is not None


def validate_date(date_string, format='%Y-%m-%d'):
    """验证日期格式"""
    if not date_string:
        return False
    
    try:
        datetime.strptime(date_string, format)
        return True
    except ValueError:
        return False


def validate_datetime(datetime_string, format='%Y-%m-%dT%H:%M:%S'):
    """验证日期时间格式"""
    if not datetime_string:
        return False
    
    try:
        datetime.fromisoformat(datetime_string.replace('Z', '+00:00'))
        return True
    except ValueError:
        return False


def validate_url(url):
    """验证URL格式"""
    if not url:
        return False
    
    pattern = r'^https?://[^\s/$.?#].[^\s]*$'
    return re.match(pattern, url) is not None


def validate_priority(priority):
    """验证任务优先级"""
    valid_priorities = ['low', 'medium', 'high', 'urgent']
    return priority in valid_priorities


def validate_status(status):
    """验证任务状态"""
    valid_statuses = ['todo', 'in_progress', 'review', 'done', 'cancelled']
    return status in valid_statuses


def validate_role(role):
    """验证用户角色"""
    valid_roles = ['owner', 'admin', 'member']
    return role in valid_roles


def validate_tags(tags):
    """验证标签格式"""
    if not tags:
        return True
    
    if not isinstance(tags, list):
        return False
    
    for tag in tags:
        if not isinstance(tag, str) or len(tag.strip()) == 0:
            return False
        if len(tag) > 50:  # 标签长度限制
            return False
    
    return len(tags) <= 10  # 最多10个标签


def sanitize_string(text, max_length=1000):
    """清理字符串"""
    if not text:
        return None
    
    # 移除HTML标签
    import re
    clean_text = re.sub(r'<[^>]+>', '', text)
    
    # 限制长度
    if len(clean_text) > max_length:
        clean_text = clean_text[:max_length]
    
    return clean_text.strip()


def validate_pagination_params(page, per_page):
    """验证分页参数"""
    if not isinstance(page, int) or page < 1:
        return False, "页码必须为正整数"
    
    if not isinstance(per_page, int) or per_page < 1 or per_page > 100:
        return False, "每页数量必须在1-100之间"
    
    return True, None


def validate_team_data(data):
    """验证团队数据"""
    from marshmallow import Schema, fields, ValidationError
    
    class TeamSchema(Schema):
        name = fields.Str(required=True, validate=lambda x: len(x.strip()) > 0)
        description = fields.Str(missing='')
    
    schema = TeamSchema()
    return schema.load(data)


def validate_project_data(data):
    """验证项目数据"""
    from marshmallow import Schema, fields, ValidationError
    
    class ProjectSchema(Schema):
        name = fields.Str(required=True, validate=lambda x: len(x.strip()) > 0)
        description = fields.Str(missing='')
        team_id = fields.Int(missing=None)
        start_date = fields.Str(missing=None)
        end_date = fields.Str(missing=None)
    
    schema = ProjectSchema()
    return schema.load(data)


def validate_task_data(data):
    """验证任务数据"""
    from marshmallow import Schema, fields, ValidationError
    
    class TaskSchema(Schema):
        title = fields.Str(required=True, validate=lambda x: len(x.strip()) > 0)
        description = fields.Str(missing='')
        assignee_id = fields.Int(missing=None)
        project_id = fields.Int(missing=None)
        priority = fields.Str(missing='medium')
        due_date = fields.Str(missing=None)
        estimated_hours = fields.Float(missing=None)
        tags = fields.List(fields.Str(), missing=[])
    
    schema = TaskSchema()
    return schema.load(data)


def validate_user_data(data, is_update=False):
    """验证用户数据"""
    from marshmallow import Schema, fields, ValidationError
    
    class UserSchema(Schema):
        username = fields.Str(required=not is_update, validate=lambda x: validate_username(x) if x else True)
        email = fields.Str(required=not is_update, validate=lambda x: validate_email(x) if x else True)
        password = fields.Str(required=not is_update, validate=lambda x: validate_password(x) if x else True)
        first_name = fields.Str(missing='')
        last_name = fields.Str(missing='')
        is_active = fields.Bool(missing=True)
        is_admin = fields.Bool(missing=False)
    
    schema = UserSchema()
    return schema.load(data)